package com.basker.pisces.service.message.converter;

import java.io.IOException;
import java.lang.reflect.Type;
import java.util.Collections;

import org.springframework.core.GenericTypeResolver;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageNotReadableException;

import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.serializer.ToStringSerializer;
import com.alibaba.fastjson.support.config.FastJsonConfig;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;

public class CustomFastJsonHttpMessageConverter extends FastJsonHttpMessageConverter {
    public CustomFastJsonHttpMessageConverter() {
        super();

        this.setSupportedMediaTypes(Collections.singletonList(MediaType.APPLICATION_JSON));

        FastJsonConfig fastJsonConfig = new FastJsonConfig();
        fastJsonConfig.setSerializerFeatures(SerializerFeature.WriteDateUseDateFormat,
                SerializerFeature.DisableCircularReferenceDetect, SerializerFeature.WriteBigDecimalAsPlain);
        fastJsonConfig.getSerializeConfig().put(Long.class, ToStringSerializer.instance);
        fastJsonConfig.getSerializeConfig().put(Long.TYPE, ToStringSerializer.instance);

        this.setFastJsonConfig(fastJsonConfig);
    }

    @Override
    public boolean canRead(Type type, Class<?> contextClass, MediaType mediaType) {
        if (type instanceof Class) {
            return canRead((Class<?>) type, mediaType);
        }

        Type resolveType = GenericTypeResolver.resolveType(type, contextClass);
        if (resolveType instanceof Class) {
            return canRead((Class<?>) resolveType, mediaType);
        }

        return canRead(mediaType);
    }

    @Override
    public Object read(Type type, Class<?> contextClass, HttpInputMessage inputMessage)
            throws IOException, HttpMessageNotReadableException {
        if (type instanceof Class) {
            return this.readInternal((Class<?>) type, inputMessage);
        }

        Type resolveType = GenericTypeResolver.resolveType(type, contextClass);
        if (resolveType instanceof Class) {
            return this.readInternal((Class<?>) resolveType, inputMessage);
        }

        return super.read(resolveType, contextClass, inputMessage);
    }
}
